﻿using System;
using System.Collections;

using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
using MUtil;

public class AutoLoadHandler : MonoBehaviour
{
    /// <summary>
    ///     加载的图片类型
    /// </summary>
    public AutoLoadManager.FileTypes FileType = AutoLoadManager.FileTypes.Texture;

    /// <summary>
    ///     加载的图片后缀名
    /// </summary>
    public AutoLoadManager.FileExtensions FileExtension = AutoLoadManager.FileExtensions.jpg;

    public bool SingleLoad = true;

    public string FileName;

    public Texture2D texture;
    private void Start()
    {
        if (texture != null)
        {
            var component = GetComponent<MeshRenderer>();
            if (component) { component.material.mainTexture = texture; }
        }
        else
        {
            if (SingleLoad) { Load(); }
        }
    }

    public void Load()
    {
        EventManager.Broadcast(AutoLoadTextureEnum.Single.ToString(), GetTextureInfo());
    }

    public AutoLoadManager.TextureInfo GetTextureInfo()
    {
        if (string.IsNullOrEmpty(FileName)) FileName = gameObject.name;

        var textureInfo = new AutoLoadManager.TextureInfo(FileName, FileType, FileExtension, (tex, b) => { });

        textureInfo.Callback = (texture2D, b) =>
        {
            if (!b) return;

            if (FileType == AutoLoadManager.FileTypes.Sprite)
                gameObject.GetComponent<Graphic>().material.mainTexture = texture2D;
            else
                gameObject.GetComponent<Renderer>().material.mainTexture = texture2D;
        };

        return textureInfo; 
    }
}